package com.gateway.filter;

import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * ai - chat 对话时路径参数校验认证情况
 */
public class AiChatTokenAuthenticationFilter implements WebFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        if (request.getPath().toString().equals("/api/ai/chat/stream")) {
            List<String> list = request.getQueryParams().get("token");
            if (list != null && !list.isEmpty()) {
                String token = list.get(0);
                // 将 token 放入header中 传递给 SecurityTokenAuthenticationWebFilter 进行校验
                ServerHttpRequest authorization = exchange.getRequest().mutate().header("Authorization", token).build();
                return chain.filter(exchange.mutate().request(authorization).build());
            }
        }
        return chain.filter(exchange);
    }
}
